package com.yeyks.app.function.aop;

import com.yeyks.app.annotation.UnUpdateCheck;
import com.yeyks.common.em.ResponseStatus;
import com.yeyks.common.exception.ServiceException;
import com.yeyks.config.service.AppInfoService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 强制更新判断
 */
@Aspect
@Component
@Slf4j
public class AppUpdateAspect {

    @Autowired
    private AppInfoService appInfoService;

    @Before(value = "com.yeyks.app.function.aop.AspectPointcut.webAllController()")
    public void beforMehhod(JoinPoint joinPoint) {
        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            UnUpdateCheck unUpdateCheck = method.getAnnotation(UnUpdateCheck.class);
            if (Objects.isNull(unUpdateCheck)) {
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                String osType = request.getHeader("osType");
                String osVersion = request.getHeader("osVersion");
                if (appInfoService.checkNeedForcedUpdate(osType, osVersion)) {
                    needForcedUpdate();
                }
            }
        } catch (Exception e) {
            if (e instanceof ServiceException) {
                throw e;
            }
        }
    }

    private void needForcedUpdate() {
        throw new ServiceException(ResponseStatus.RS_FORCED_UPDATE.getCode(), ResponseStatus.RS_FORCED_UPDATE.getMsg());
    }

}
